package com.itcast.myrpc.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * @program: bio_tcp
 * @description: SimpleChannelInboundHandler 可以实现直接缓存的回收
 * 通过SimpleChannelInboundHandler进行自动释放channel的byteBuf缓存
 * @author: zhanghz001
 * @create: 2021-02-22 09:18
 **/
public class MyClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext,
                                ByteBuf msg) throws Exception {
        System.out.println("客户端接收到了服务器的消息 : "
                + msg.toString(CharsetUtil.UTF_8));
    }
    
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        
        //向服务器发送请求
        String msg = "hello";
        System.out.println("客户端开始发送");
        ctx.writeAndFlush(Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8));
        // ctx.writeAndFlush(111);
    }
    
    /**
     * 处理异常
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
